//
//  AuthoriVC.swift
//  kxf
//
//  Created by Mac on 2024/3/19.
//

import Foundation
import UIKit
import Photos
import MCToast

class AuthoriVC : WHBaseViewVC {
    
    var phone = ""
    var type = "wechat"
    var msgDict = NSDictionary()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        sendRequest()
    }
    lazy var segmentVm : TypeSegmentVM = {
        let vm = TypeSegmentVM.init(frame: CGRect.init(x: kFitWidth(65), y: kFitWidth(45), width: 0, height: 0))
        vm.leftButton.setTitle("微信", for: .normal)
        vm.rightButton.setTitle("支付宝", for: .normal)
        vm.leftTapBlock = {()in
            self.type = "wechat"
            self.updateUI(isWeChat: true)
        }
        vm.rightTapBlock = {()in
            self.type = "alipay"
            self.updateUI(isWeChat: false)
        }
        return vm
    }()
    lazy var bgWhiteImgView : UIImageView = {
        let img = UIImageView()
        img.setImgLocal(imgName: "mine_qrcode_bg")
        img.isUserInteractionEnabled = true
        
        return img
    }()
    lazy var qrCodeImgView : UIImageView = {
        let img = UIImageView()
        
        return img
    }()
    lazy var codeLabel : UILabel = {
        let lab = UILabel()
        lab.backgroundColor = WHColor_16(colorStr: "F8F8F8")
        lab.textColor = .black
        lab.font = .systemFont(ofSize: 20, weight: .regular)
        lab.textAlignment = .center
        lab.layer.cornerRadius = kFitWidth(22)
        lab.clipsToBounds = true
        lab.adjustsFontSizeToFitWidth = true
        
        return lab
    }()
    lazy var copyBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("复制商户号", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        btn.setBackgroundImage(UIImage.init(named: "qrcode_btn_bg"), for: .normal)
        btn.backgroundColor = .clear
        btn.titleEdgeInsets = UIEdgeInsets(top: -kFitWidth(5), left: 0, bottom: 0, right: 0)
        
        btn.addTarget(self, action: #selector(copyAction), for: .touchUpInside)
        
        return btn
    }()
    lazy var saveBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("下载保存", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        btn.setBackgroundImage(UIImage.init(named: "qrcode_btn_bg"), for: .normal)
        btn.backgroundColor = .clear
        btn.titleEdgeInsets = UIEdgeInsets(top: -kFitWidth(5), left: 0, bottom: 0, right: 0)
        
        btn.addTarget(self, action: #selector(saveAction), for: .touchUpInside)
        
        return btn
    }()
    lazy var shareBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("分享转发", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        btn.setBackgroundImage(UIImage.init(named: "qrcode_btn_bg"), for: .normal)
        btn.backgroundColor = .clear
        btn.titleEdgeInsets = UIEdgeInsets(top: -kFitWidth(5), left: 0, bottom: 0, right: 0)
        
        btn.addTarget(self, action: #selector(shareAction), for: .touchUpInside)
        return btn
    }()
}

extension AuthoriVC{
    @objc func copyAction(){
        let pasteboard = UIPasteboard.general
        if self.type == "wechat"{
            pasteboard.string = "\(self.msgDict["weChatCode"]as? String ?? "")"
        }else{
            pasteboard.string = "\(self.msgDict["aliCode"]as? String ?? "")"
        }
        
        MCToast.mc_text("商户号已复制")
    }
    @objc func shareAction()  {
        let message =  WXMediaMessage()
        
        let imageObject =  WXImageObject()
        let img = qrCodeImgView.mc_makeImage()
        imageObject.imageData = img.pngData()!
        message.mediaObject = imageObject
        let req =  SendMessageToWXReq()
        req.bText = false
        req.message = message
        req.scene = Int32(WXSceneSession.rawValue)
        WXApi.send(req)

    }
}

extension AuthoriVC{
    func initUI() {
        initNavi(titleStr: "授权")
        
        view.addSubview(scrollView)
        scrollView.frame = CGRect.init(x: 0, y: getNavigationBarHeight(), width: SCREEN_WIDHT, height: SCREEN_HEIGHT - getNavigationBarHeight())
        scrollView.backgroundColor = WHColorWithAlpha(colorStr: "F10E0E", alpha: 0.09)
        
        scrollView.addSubview(bgWhiteImgView)
        bgWhiteImgView.addSubview(segmentVm)
        bgWhiteImgView.addSubview(qrCodeImgView)
        
        scrollView.addSubview(codeLabel)
        scrollView.addSubview(copyBtn)
        scrollView.addSubview(saveBtn)
        scrollView.addSubview(shareBtn)
        
        setConstrait()
    }
    func setConstrait() {
        bgWhiteImgView.snp.makeConstraints { make in
            make.centerX.lessThanOrEqualToSuperview()
            make.top.equalTo(kFitWidth(22))
            make.width.equalTo(kFitWidth(343))
            make.height.equalTo(kFitWidth(406))
        }
        qrCodeImgView.snp.makeConstraints { make in
            make.centerX.lessThanOrEqualToSuperview()
            make.top.equalTo(kFitWidth(138))
            make.width.height.equalTo(kFitWidth(240))
        }
        codeLabel.snp.makeConstraints { make in
            make.centerX.lessThanOrEqualToSuperview()
            make.top.equalTo(bgWhiteImgView.snp.bottom).offset(kFitWidth(21))
            make.width.equalTo(kFitWidth(190))
            make.height.equalTo(kFitWidth(44))
        }
        copyBtn.snp.makeConstraints { make in
            make.left.equalTo(kFitWidth(13))
            make.top.equalTo(codeLabel.snp.bottom).offset(kFitWidth(34))
            make.width.equalTo(kFitWidth(108))
            make.height.equalTo(kFitWidth(44))
        }
        saveBtn.snp.makeConstraints { make in
            make.centerX.lessThanOrEqualToSuperview()
            make.top.width.height.equalTo(copyBtn)
        }
        shareBtn.snp.makeConstraints { make in
            make.left.equalTo(kFitWidth(249))
            make.top.width.height.equalTo(copyBtn)
        }
    }
    func updateUI(isWeChat:Bool) {
        qrCodeImgView.image = nil
        if isWeChat{
            qrCodeImgView.setImgUrl(urlString: "\(self.msgDict["weChatUrl"]as? String ?? "")")
            codeLabel.text = "\(self.msgDict["weChatCode"]as? String ?? "")"
        }else{
            qrCodeImgView.setImgUrl(urlString: "\(self.msgDict["aliUrl"]as? String ?? "")")
            codeLabel.text = "\(self.msgDict["aliCode"]as? String ?? "")"
        }
    }
}

extension AuthoriVC{
    func sendRequest(){
        WHNetworkUtil.shareManager().GET(urlString: "\(URL_authori_code)?phone=\(phone)") { responseObject in
            DLLog(message: "\(responseObject)")
            
            if responseObject["code"]as? Int ?? -1 == 200{
                self.msgDict = responseObject["data"]as? NSDictionary ?? [:]
                self.updateUI(isWeChat:true)
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "")", viewController: self)
            }
        }
    }
}

extension AuthoriVC{
    @objc func saveAction() {
        PHPhotoLibrary.requestAuthorization { (status) in
            DispatchQueue.main.async {
                if status == .restricted || status == .denied{
                    self.presentAlertVc(confirmBtn: "打开", message: "无访问相册权限，是否去打开权限?", title: "提示", cancelBtn: "取消", handler: { (actions) in
                        self.openUrl(urlString: UIApplication.openSettingsURLString)
                    }, viewController: self)
                }else{
                    MCToast.mc_loading(text: "保存中", autoClearTime: 30)
                    let image = self.qrCodeImgView.mc_makeImage()
                    UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.saveImage(image:didFinishSavingWithError:contextInfo:)), nil)
                }
            }
        }
    }
    @objc private func saveImage(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject){
        MCToast.mc_remove()
        if error != nil{
            self.presentAlertVcNoAction(title: "保存失败", viewController: self)
        }else{
            MCToast.mc_text("已保存到相册！")
        }
    }
}
